<template>
    <div id="jha" class="w-h-100 pos-r flex-1 apply-container page-public-s"
        style="box-sizing: border-box;overflow:hidden;">
        <div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px;">
            <div v-if="$hasPer('JHA:add') || $hasPer('JHA:batchUpload') || $hasPer('JHA:batchDown') || $hasPer('JHA:excel')"
                style="box-sizing: border-box;">
                <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" ref="queryForm" :inline="true">
                        <el-form-item>
                            <el-button v-if="$hasPer('JHA:add')" @click="nodeClick('')" icon="ele-Plus" type="primary">
                                新增 </el-button>
                            <el-button v-if="$hasPer('JHA:batchUpload')" @click="funClick(0)" icon="ele-Upload"> 批量上传
                            </el-button>
                            <el-button v-if="$hasPer('JHA:batchDown')" @click="funClick(1)" icon="ele-Download"> 模板下载
                            </el-button>
                            <el-button v-if="$hasPer('JHA:excel')" @click="handleExport" icon="ele-Download"> 导出数据
                            </el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <div style="box-sizing: border-box;" class="flex-1 pos-r">
                <div class="pos-a w-h-100" style="box-sizing: border-box;">
                    <el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px;">
                        <div style="" class="w-h-100 ver-flex">
                            <div class="flex-1 pos-r">
                                <div class="pos-a w-h-100">
                                    <el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border
                                        v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险管控分析单元"
                                            align="center">
                                            <el-table-column :show-overflow-tooltip="true" min-width="200"
                                                align="center">
                                                <template #header>
                                                    <SearchModel typeId="s_Unit" typeVal="select"
                                                        @selectFocus="selectFocus(0)" @searchHandel="searchHandel"
                                                        :basicsInfo="basicsInfo" />
                                                </template>
                                                <template #default="scope">
                                                    <span v-if="scope.row.v_AnalysisUnitName">{{
                                                        scope.row.v_AnalysisUnitName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="车间/班组"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_RiskPartitionName">{{
                                                    scope.row.v_RiskPartitionName }}</span>
                                                <span v-else> - </span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险点名称"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_RiskPoint">{{ scope.row.v_RiskPoint }}</span>
                                                <span v-else> - </span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="检查内容"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_CheckContent">{{ scope.row.v_CheckContent
                                                    }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="标准要求"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_Standard">{{ scope.row.v_Standard }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="210" :show-overflow-tooltip="true"
                                            label="产生偏差导致的主要事故类型" align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_AccidentType">{{ scope.row.v_AccidentType
                                                    }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="现有控制措施"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_ControlMeasure">{{ scope.row.v_ControlMeasure
                                                    }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险评价"
                                            align="center">

                                            <el-table-column :show-overflow-tooltip="true" label="L" align="center">
                                                <template #default="scope">
                                                    <span v-if="scope.row.n_RiskAssessmentL">{{
                                                        scope.row.n_RiskAssessmentL }}</span>
                                                    <span v-else>-</span>
                                                </template>
                                            </el-table-column>

                                            <el-table-column :show-overflow-tooltip="true" label="S" align="center">
                                                <template #default="scope">
                                                    <span v-if="scope.row.n_RiskAssessmentS">{{
                                                        scope.row.n_RiskAssessmentS }}</span>
                                                    <span v-else>-</span>
                                                </template>
                                            </el-table-column>

                                            <el-table-column :show-overflow-tooltip="true" label="R" align="center">
                                                <template #default="scope">
                                                    <span v-if="scope.row.n_RiskAssessmentR">{{
                                                        scope.row.n_RiskAssessmentR }}</span>
                                                    <span v-else>-</span>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="风险程度"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.n_RiskLevel === 0" style="color: #409EFF;">{{
                                                    scope.row.v_RiskLevelName }}</span>
                                                <span v-if="scope.row.n_RiskLevel === 1" style="color: #E6A23C;">{{
                                                    scope.row.v_RiskLevelName }}</span>
                                                <span v-if="scope.row.n_RiskLevel === 2" style="color: #FF7F00;">{{
                                                    scope.row.v_RiskLevelName }}</span>
                                                <span v-if="scope.row.n_RiskLevel === 3" style="color: #F56C6C;">{{
                                                    scope.row.v_RiskLevelName }}</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="纠正措施"
                                            align="center">
                                            <template #default="scope">
                                                <span v-if="scope.row.v_CorrectiveMeasure">{{
                                                    scope.row.v_CorrectiveMeasure }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>

                                        <el-table-column width="180" label="操作" align="center" fixed="right">
                                            <el-table-column :show-overflow-tooltip="true" width="180" align="center">
                                                <template #header>
                                                    <el-button class="icon-e" @click='searchClick' icon="ele-Search"
                                                        size="small" type="primary" text> 查询 </el-button>
                                                    <el-button class="icon-e clear-bg"
                                                        style="background-color: transparent !important;" size="small"
                                                        @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                                </template>
                                                <template #default="scope">
                                                    <!-- <el-button @click="detailHandle(scope.row.id)" class="icon-e" icon="ele-View" size="small" text type="success">详情</el-button> -->
                                                    <el-button v-if="$hasPer('JHA:edit')" @click="nodeClick(scope.row)"
                                                        class="icon-e" icon="ele-Edit" size="small" text
                                                        type="primary">编辑</el-button>
                                                    <el-button v-if="$hasPer('JHA:del')"
                                                        @click="deleteHandle(scope.row.id, getData)" class="icon-e"
                                                        icon="ele-Delete" size="small" text type="danger">删除</el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
                                <el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize"
                                    :total="totalRows" :page-sizes="[10, 20, 50, 100]" small background
                                    @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                    layout="total, sizes, prev, pager, next, jumper" class="w-h-100" />
                            </div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <AddEditLs :repairInfo="repairInfo" :isUseDialog="isUseDialog" :commonInfo="commonInfo" @updateData="getData"
            @cancelUseClick="cancelUseClick" @controlUseClick="controlUseClick" />
        <MassUpload :isBase="true" uploadType="jha" :neddUrl="needUrl" :isUseDialog="massDialog"
            :commonInfo="commonInfo" @updateData="getData" @cancelMassClick="cancelMassClick"
            @controlMassClick="controlMassClick" />
        <!-- 详情 -->
        <DetailModel :detailInfo="detailInfo" :MdetailDialog="MdetailDialog" labelWidth="140px"
            @cancelDetailClick="cancelDetailClick" />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted, reactive, toRaw, toRefs } from 'vue';
import getTableData from '/@/utils/getTableData';
import AddEditLs from '../component/sms/add-edit-ls.vue';
import MassUpload from '../component/sms/mass-upload.vue';
import SearchModel from '../component/search-model.vue';
import DetailModel from '../component/detail-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';

import {
    SMSDCLSPage,
    SMSDCLSDelete,
    SMSDCLSBathAddByExcel,
    SMSDCAnalysisUnitList,
    SMSDCJHADetail, // 详情暂时不要了
} from '/@/api/centerControl/sms';
import { ElMessageBox, ElMessage } from 'element-plus';
import { nextTick } from 'process';

export default defineComponent({
    name: 'jha',
    components: { AddEditLs, MassUpload, SearchModel, DetailModel },
    setup(props) {
        const isUseDialog = ref(false); // 新增/编辑弹出框隐藏/显示
        const repairInfo = ref(); // 传递子组件数据
        const massDialog = ref(false);
        const baseUrl = import.meta.env.VITE_API_URL;
        const commonInfo = ref();

        /*** 新增/编辑 */
        const nodeClick = (val: any) => {
            repairInfo.value = val === '' ? '' : JSON.stringify(val);
            isUseDialog.value = true;
        }

        /*** HAZOP取消事件 */
        const cancelUseClick = () => {
            isUseDialog.value = false;
        }

        /*** HAZOP提交事件 */
        const controlUseClick = () => {
            isUseDialog.value = false;
        }

        /*** HAZOP删除事件 */
        const deleteHandle = (val: number, updateFun: Function) => {
            ElMessageBox.confirm('请确定删除此条数据？', '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(async () => {
                    let param = { id: val };
                    try {
                        let res: any = await SMSDCLSDelete(param);
                        if (res.success) {
                            updateFun()
                        }
                    } catch (err) { return }
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '已取消',
                    })
                })
        }

        /*** 上传/下载点击事件 */
        const funClick = (num: number) => {
            console.log(num, 'num')
            if (num === 0) {
                massDialog.value = true;
            }
            if (num === 1) {
                // window.open('http://xxxx','_blank') // 打开新页面
                window.location.href = baseUrl + '/Upload/SMS/ExcelTempFiles/安全评价记录LS-导入模版.xlsx'; // 当前页面中打开
            }
        }

        /*** 批量上传取消事件 */
        const cancelMassClick = () => {
            massDialog.value = false;
        }

        /*** 批量上传提交事件 */
        const controlMassClick = () => {
            massDialog.value = false;
        }

        /*** ================================= 详情类数据操作 =================================  */
        const MdetailDialog = ref(false);
        const detailInfo = ref();
        /*** 获取详情接口数据 */
        const getDetailFun = async (id: number) => {
            let res: any = await SMSDCJHADetail({ id: id }); // 详情
            if (res.success) {
                let setArr: any = [];
                let detailObj: any = {};
                detailObj['风险分析单元'] = res.data.v_AnalysisUnitName;
                detailObj['工作任务'] = res.data.v_Task;
                detailObj['工作步骤'] = res.data.v_WorkStage;
                detailObj['危害或潜在事件'] = res.data.v_Event;
                detailObj['主要后果'] = res.data.v_Consequence;
                detailObj['现有安全控制措施'] = res.data.v_ControlMeasureNow;
                detailObj['风险评估-严重性S'] = res.data.v_RiskAssessmentS;
                detailObj['风险评估-可能性L'] = res.data.v_RiskAssessmentL;
                detailObj['风险评估-严重度R'] = res.data.v_RiskAssessmentR;
                detailObj['风险等级'] = res.data.v_RiskLevelName;
                detailObj['建议改正/控制措施'] = res.data.v_DCMeasure;
                detailObj['评价员'] = res.data.v_Valuator;
                detailObj['分析日期'] = res.data.d_ParsingDate ? res.data.d_ParsingDate.split(' ')[0] : '-';
                detailObj['记录人'] = res.data.v_Notekeeper;
                detailObj['记录日期'] = res.data.d_WriteTime ? res.data.d_WriteTime.split(' ')[0] : '-';
                detailObj['负责人'] = res.data.v_Principal;
                detailObj['负责人确认日期'] = res.data.d_PrincipalSigTime ? res.data.d_PrincipalSigTime.split(' ')[0] : '-';
                setArr = [{
                    formTitle: '基础信息',
                    type: 'form',
                    info: detailObj,
                }];
                detailInfo.value = setArr;
                MdetailDialog.value = true;
            }
        }
        /*** 详情 */
        const detailHandle = (id: number) => {
            // getDetailFun(id);
        }
        /*** 详情关闭事件 */
        const cancelDetailClick = () => {
            MdetailDialog.value = false;
        }
        /*** ================================= 详情类数据操作 =================================  */

        /*** ================================= 查询类数据操作 =================================  */
        let searchObj: any = reactive({});
        const basicsInfo: any = ref([]);
        const searInfo: any = ref();

        /*** 获取需要查询的数据 */
        const searchHandel = (val: any) => {
            searInfo.value = val;
        }

        /*** 下拉框获取焦点事件 */
        const selectFocus = (num: number) => {
            console.log(num, '下拉框获取焦点事件')
        }

        /*** 查询按钮 */
        const searchClick = () => {
            let newObj = Object.keys(searInfo.value);
            if (newObj.length !== 0) {
                newObj.map((i: any) => {
                    searchObj[i] = searInfo.value[i];
                });
            }
        };

        /*** 重置按钮 */
        const resetClick = () => {
            searInfo.value = {};
            let newObj = Object.keys(searchObj);
            if (newObj.length !== 0) {
                newObj.map((i: any) => {
                    searchObj[i] = ''
                });
            }
            initInfoFun();
        };

        let unitArr: any = [];
        // 获取数据
        const getFun = async () => {
            let ras: any = await SMSDCAnalysisUnitList({}); // 风险分析单元
            if (ras.success && ras.data.length !== 0) {
                ras.data.map((item: any) => {
                    item.label = item.v_RiskPartitionName ? item.v_RiskPartitionName + '——' + item.v_Name : item.v_Name;
                    item.value = item.id;
                });
                unitArr = ras.data;
                commonInfo.value = ras.data;
            }
        }

        /*** 初始化数据 */
        const initInfoFun = () => {
            basicsInfo.value = [{
                typeId: 's_Unit', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
                typeNam: '', // 输入类型(number,text等) --- 选填
                searchVal: 'l_AnalysisUnitId', // 查询字段 --- 必填
                defaultVal: '', // 字段默认值 --- 选填
                placeholder: '风险管控分析单元', // placeholder数据
                defaultProp: unitArr, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
                eventType: 'change', // 事件类型（如burl/change等） --- 选填
                defaultEvent: 'unitChange', // 事件名称 --- 选填
            }
            ]
        }

        onMounted(() => {
            nextTick(async () => {
                await getFun();
                initInfoFun();
            });
        });
        /*** ================================= 查询类数据操作 =================================  */

        /*** ================================= 导出数据函数操作 ================================= */
        const excelRef: any = ref(null);
        const handleExport = () => {
            if (excelRef.value) {
                if (excelRef.value.data.length !== 0) {
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['风险分析单元'] = item.v_AnalysisUnitName ? item.v_AnalysisUnitName : '-';
                        tableObj['车间/班组'] = item.v_RiskPartitionName ? item.v_RiskPartitionName : '-';
                        tableObj['风险点名称'] = item.v_RiskPoint ? item.v_RiskPoint : '-';
                        tableObj['检查内容'] = item.v_CheckContent ? item.v_CheckContent : '-';
                        tableObj['标准要求'] = item.v_Standard ? item.v_Standard : '-';
                        tableObj['产生偏差导致的主要事故类型'] = item.v_AccidentType ? item.v_AccidentType : '-';
                        tableObj['现有控制措施'] = item.v_ControlMeasure ? item.v_ControlMeasure : '-';
                        tableObj['风险评价-L'] = item.n_RiskAssessmentL ? item.n_RiskAssessmentL : '-';
                        tableObj['风险评价-S'] = item.n_RiskAssessmentS ? item.n_RiskAssessmentS : '-';
                        tableObj['风险评价-R'] = item.n_RiskAssessmentR ? item.n_RiskAssessmentR : '-';
                        tableObj['风险程度'] = item.v_RiskLevelName ? item.v_RiskLevelName : '-';
                        tableObj['纠正措施'] = item.v_CorrectiveMeasure ? item.v_CorrectiveMeasure : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel, 'JHA(工作危害分析法).xlsx');
                } else {
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }
        /*** ================================= 导出数据函数操作 ================================= */

        return {
            ...getTableData(SMSDCLSPage, {}, searchObj),

            repairInfo,
            isUseDialog,
            nodeClick,
            cancelUseClick,
            controlUseClick,
            deleteHandle,
            selectFocus,
            commonInfo,

            funClick,
            needUrl: SMSDCLSBathAddByExcel,
            massDialog,
            cancelMassClick,
            controlMassClick,

            // 导出Excel
            excelRef,
            handleExport,

            // 详情
            MdetailDialog,
            detailHandle,
            detailInfo,
            cancelDetailClick,

            // 查询事件
            basicsInfo,
            searchHandel,
            searchClick,
            resetClick,
        }
    },
})
</script>
<style lang="scss">
@import '../style/public.scss';
</style>
<style scoped lang="scss">
ul {
    list-style: none;

    li {
        cursor: pointer;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        text-align: center;
        padding: 10px 0;
    }
}

.search-s {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    width: 100%;

    .search-s-l {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        width: 98%;
    }
}

#jha {
    .box-f {
        :deep(.el-form-item__label) {
            padding: 0;
        }
    }

    :deep(.el-card__body) {
        height: 100%;
    }

    :deep(.el-card) {
        border: none !important;
    }

    .upload-demo {
        margin-left: 12px;
        margin-top: 2px;
    }

    .icon-e {
        :deep(.el-icon) {
            margin-right: 0px !important;
        }
    }
}

.clear-bg {
    background-color: transparent !important;
}
</style>